package com.wushi.lenovo.asia5b.app_ui.good.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderItemFragmentView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.OrderItemFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_event.OrderReceiveEvent;
import com.wushi.lenovo.asia5b.app_event.PlaceOrderEvent;
import com.wushi.lenovo.asia5b.app_event.PostPackEvent;
import com.wushi.lenovo.asia5b.app_model.credit.bean.TopupInfoBean;
import com.wushi.lenovo.asia5b.app_model.good.bean.PriceDetailType;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.OrderGoodBean;
import com.wushi.lenovo.asia5b.app_model.good.orderitem.OrderItemModel;
import com.wushi.lenovo.asia5b.app_model.good.orderitem.OrderItemType;
import com.wushi.lenovo.asia5b.app_model.other.CountType;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_ui.good.activity.DiffCheckActivity;
import com.wushi.lenovo.asia5b.app_ui.good.activity.SecondCheckActivity;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.listener.ButtonListener;
import com.wushi.lenovo.asia5b.app_ui.good.listener.OrderAdapterListener;
import com.wushi.lenovo.asia5b.app_ui.h5.GoodsDetailsActivity;
import com.wushi.lenovo.asia5b.app_ui.orderdetail.OrderDetailActivity;
import com.wushi.lenovo.asia5b.app_ui.orderdetail.PriceDetailActivity;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.CancelSureDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.NgDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.OrderCancelDialog;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/1/23.
 * 订单页面的pageradapter中的页面
 */
public class OrderItemFragment extends BaseMvpFragment<OrderItemFragmentView, OrderItemFragmentPresenter>
        implements OrderItemFragmentView {
    @BindView(R.id.rv_order)
    public RecyclerView mRecyclerView;
    @BindView(R.id.auto_order)
    public AutoRefreshLayout auto;
    @BindView(R.id.tv_order_notice)
    public TextView tv_order_notice;
    @BindView(R.id.cons_order_pack_vessel)
    public ConstraintLayout cons_order_pack_vessel;
    @BindView(R.id.ll_order_bottom)
    public LinearLayout ll_order_bottom;
    @BindView(R.id.tv_order_expan)
    public TextView tv_order_expan;
    @BindView(R.id.cons_order_detail_vessel)
    public ConstraintLayout cons_order_detail_vessel;
    @BindView(R.id.tv_order_pack)
    public TextView tv_order_pack;
    @BindView(R.id.tv_order_totalactualweight)
    public TextView tv_order_totalactualweight;
    @BindView(R.id.tv_order_totalvolweight)
    public TextView tv_order_totalvolweight;
    @BindView(R.id.tv_order_totalm3)
    public TextView tv_order_totalm3;
    @BindView(R.id.iv_order_totalvolweight_icon)
    public ImageView iv_order_totalvolweight_icon;
    public OrderItemType type = null;
    public OrderAdapter mAdapter;
    public final List<OrderItemModel> mDatas = new ArrayList<>();
    public View emptyView;

    private ButtonListener buttonListener = new ButtonListener() {

        @Override
        public void actionClick(OrderGoodBean.ActionBean actionBean, OrderItemModel orderItemModel, OrderGoodBean bean) {
            if (actionBean == null) {
                return;
            }
            String actionCode = actionBean.getCode();
            if (TextUtils.isEmpty(actionCode)) {
                d("--->>>>>>>>---actionCode.isEmpty");
                return;
            }
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("member_id", UserInfo.getMemberId());
            OrderGoodBean.Popup_buttonBean popup_button_left = actionBean.getPopup_button_left();
            Map<String, String> leftButtonParam = popup_button_left.getParam();//当点击左边button中里面的参数

            if (TextUtils.equals(actionCode, "button_cancel_order")) {//除了这个单独弹窗,其他都是统一的
                OrderCancelDialog orderCancelDialog = new OrderCancelDialog((BaseAppCompatActivity) getActivity(), actionBean);
                orderCancelDialog.show();
                orderCancelDialog.setCallBack((WCallBack<OrderCancelDialog.CancelBean>) cancelBean -> {
                    paramMap.put("parcel_status", "null");//包裹状态,暂时不予理会
                    paramMap.put("cancel_status", cancelBean.cancel_status + "");
                    paramMap.put("reason", cancelBean.reason + "");
                    if (leftButtonParam != null) {
                        paramMap.putAll(leftButtonParam);
                    }
                    getPresenter().button_order(paramMap, popup_button_left.getAjaxUrlSuffix());
                });
            } else if (TextUtils.equals(actionCode, "button_pay_order")) {//二次付款
                if (orderItemModel.getOrder_parcel() != null && orderItemModel.getOrder_parcel().size() > 0) {
                    List<OrderGoodBean> goodsBeanList = new ArrayList<>();
                    List<Integer> idList = new ArrayList<>();
                    for (OrderGoodBean orderGoodBean : orderItemModel.getOrder_parcel()) {
                        idList.add(orderGoodBean.getId());
                        goodsBeanList.add(orderGoodBean);
                    }
                    SecondCheckActivity.startOrderCheckPayActivity(mContext, (Serializable) idList, (Serializable) goodsBeanList);
                }
            } else if (TextUtils.equals(actionCode, "button_pay_price_diff")) {//差价付款
                if (bean != null) {
                    List<OrderGoodBean> goodsBeanList = new ArrayList<>();
                    List<Integer> idList = new ArrayList<>();
                    idList.add(bean.getId());
                    goodsBeanList.add(bean);
                    DiffCheckActivity.startDiffCheckActivity(mContext, (Serializable) idList, (Serializable) goodsBeanList);
                }
            } else {
                CancelSureDialog dialog = getCancelSureDialog(actionBean.getPopup_content(), popup_button_left.getName()
                        , actionBean.getPopup_button_right().getName());
                dialog.setCallBack((s) -> {
                    if (leftButtonParam != null) {
                        paramMap.putAll(leftButtonParam);
                    }
                    getPresenter().button_order(paramMap, popup_button_left.getAjaxUrlSuffix());
                });
                dialog.show();
            }
        }

        @Override
        public void problemClick(OrderGoodBean bean) {
            new NgDialog(getContext(), bean).show();
        }
    };

    public CancelSureDialog getCancelSureDialog(String titleContent, String leftContent, String rightContent) {
        CancelSureDialog dialog = new CancelSureDialog.Builder(getContext())
                .setContent(titleContent)
                .setLeftContent(leftContent)
                .setRightContent(rightContent)
                .build();
        return dialog;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        type = (OrderItemType) getArguments().getSerializable("type");
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_orderitem;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initView();

        initEvent();
    }

    @Override
    protected void lazyFetchData() {

        initData();

    }

    @Override
    protected void initView() {
        EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_pi_notice), getString(R.string.shopcar_pi_notice_key),
                tv_order_notice, WebUrlType.shopcar_pi);
        if (auto != null)
            ((RefreshViewManager) mActivity).addView(auto);
        emptyView = View.inflate(getContext(), R.layout.empty_orderitem, null);
        setEmptyViewContent();

        mAdapter = OrderAdapter.newInstance(type, mDatas, orderAdapterListener);
        mAdapter.setButtoListener(buttonListener);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

        resetView();
    }

    OrderAdapterListener orderAdapterListener = new OrderAdapterListener() {
        @Override
        public void priceDetail(OrderGoodBean bean) {
            PriceDetailActivity.startPriceDetailActivity(getContext(), bean, PriceDetailType.orderpack);
        }

        @Override
        public void goodsDetail(OrderGoodBean bean) {
            GoodsDetailsActivity.startGoodsDetailsActivity(getContext(), bean.getProduct_id());
        }

        @Override
        public void orderDetail(OrderItemModel model) {
            OrderDetailActivity.startOrderDetailActivity(getContext(), model.getOrder_id(), type);
        }

        @Override
        public void selectGoods(OrderGoodBean bean) {
            selectGoods2(bean);
        }
    };

    public void selectGoods2(OrderGoodBean bean) {

    }

    protected void resetView() {
        mDatas.clear();
        mAdapter.notifyDataSetChanged();
    }

    protected void setEmptyViewContent() {
        ImageView imageView = emptyView.findViewById(R.id.iv_empty_icon);
        TextView content = emptyView.findViewById(R.id.tv_empty_content);
        content.setText(type.getEmptyText());
        imageView.setImageResource(type.getEmptyIcon());
    }

    @Override
    protected void initData() {
        if (auto != null)
            auto.autoRefresh();
    }

    protected void getOrders(int refresh) {
        getPresenter().getOrders(type, refresh);
    }

    @Override
    protected void initEvent() {
        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                getOrders(1);
            });
        if (auto != null)
            auto.setOnLoadMoreListener(refreshLayout -> {
                getOrders(2);
            });
    }

    @OnClick({
            R.id.ll_order_bottom
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_order_bottom:
                break;
            default:
                break;
        }

    }

    @Override
    public void getOrdersResult(List<OrderItemModel> list, int page, int sumPage) {
        if (page == 1) {
            mDatas.clear();
        }
        if (list != null) {
            //检查前后是否有一样的订单号,如果有,排除掉
            if (mDatas.size() > 0 && list.size() > 0) {
                OrderItemModel model1 = mDatas.get(mDatas.size() - 1);
                OrderItemModel model2 = list.get(0);
                if (TextUtils.equals(model1.getOrder_no(), model2.getOrder_no())) {
                    try {
                        model1.getOrder_parcel().addAll(model2.getOrder_parcel());
                        list.remove(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            mDatas.addAll(list);
        }
        mAdapter.setEmptyView(emptyView);
        if (page == sumPage || mDatas.size() == 0) {
            if (auto != null)
                auto.setEnableLoadMore(false);
        } else {
            if (auto != null)
                auto.setEnableLoadMore(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        super.showLoadingFailureError(throwable);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }


    @Override
    public void button_orderResult(ResultModel resultModel, Map<String, Object> map) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            getOrders(1);
        }
    }

    @Override
    public void countResult(int total) {
        Fragment parentFragment = getParentFragment();
        if (parentFragment != null) {
            if (parentFragment instanceof OrderFragment) {
                OrderFragment fragment = (OrderFragment) parentFragment;

                switch (type) {
                    case Verification: {
                        fragment.getPresenter().getCount(CountType.Order_Verification);
//                        fragment.setTabCount(0, total);
                    }
                    break;
                    case Payment: {
                        fragment.getPresenter().getCount(CountType.Order_Payment);
//                        fragment.setTabCount(1, total);
                    }
                    break;
                    case Delivery: {
                        fragment.getPresenter().getCount(CountType.Order_Delivery);
//                        fragment.setTabCount(2, total);
                    }
                    break;
                    case History: {
                        fragment.getPresenter().getCount(CountType.Order_History);
//                        fragment.setTabCount(3, total);
                    }
                    break;
                    case Problematic: {
                        fragment.getPresenter().getCount(CountType.Order_Problematic);
//                        fragment.setTabCount(4, total);
                    }
                    break;
                    default:
                        break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
//                    getOrders(1);
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                hasFetchData = false;
                resetView();
            }

        }


    }


    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPlaceOrderEvent(PlaceOrderEvent event) {
        if (event != null) {
            //提交订单后,待确认订单需要刷新数据
            if (type == OrderItemType.Verification) {
                getOrders(1);
            }
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderReceiveEvent(OrderReceiveEvent event) {
        if (event != null) {
            //订单收货
            if (type == OrderItemType.Delivery || type == OrderItemType.History) {
                getOrders(1);
            }
        }


    }

    /**
     * 申请打包
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPostPackEvent(PostPackEvent event) {
        if (type == OrderItemType.Verification||type == OrderItemType.Payment) {
            //刷新处理中
            d("--->>>>>>>>---onPostPackEvent:刷新处理中");
            getOrders(1);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) //在ui线程执行
    public void onOrderPayEvent(OrderPayEvent event) {
        Timber.d("--->>>>>>>>---onOrderPayEvent");
        if (event != null && event.resultModel.isSuccess()) {
            if (event.topupInfoBean != null) {
                int orderPaymentType = event.topupInfoBean.OrderPaymentType;
                if (orderPaymentType == TopupInfoBean.OrderPaymentType_fist) {
                    if (event.topupInfoBean.goodsType == 0 || event.topupInfoBean.goodsType == 1) {//代购商品
                        //刷新处理中
                        if (type == OrderItemType.Verification) {
                            d("--->>>>>>>>---onOrderPayEvent:刷新处理中");
                            getOrders(1);
                        }
                    } else {//自营商品跳到发货中
                        //刷新发货中
                        if (type == OrderItemType.Delivery) {
                            d("--->>>>>>>>---onOrderPayEvent:刷新发货中");
                            getOrders(1);
                        }
                    }

                } else if (orderPaymentType == TopupInfoBean.OrderPaymentType_second) {
                    //刷新代付款/代发货
                    if (type == OrderItemType.Payment || type == OrderItemType.Delivery) {
                        d("--->>>>>>>>---onOrderPayEvent:刷新代付款和代发货");
                        getOrders(1);
                    }
                } else if (orderPaymentType == TopupInfoBean.OrderPaymentType_diff) {
                    //刷新代付款
                    if (type == OrderItemType.Payment) {
                        d("--->>>>>>>>---onOrderPayEvent:刷新代付款");
                        getOrders(1);
                    }
                }
            }
        }


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}